﻿Imports System.ComponentModel

<DefaultEvent("ProviderSelected")> _
Public Class ProviderSearchBoxCtrl

    Private dv As New DataView
    Private pg As New DataGridView
    Private tp As New Panel
    Private host As ToolStripControlHost
    Private popup As ToolStripDropDown = New ToolStripDropDown()

    Private _ConnectionString As String
    <Browsable(True), DefaultValue(""), Description("Connection string")> _
    Public Property zConnectionString() As String
        Get
            Return _ConnectionString
        End Get
        Set(ByVal value As String)
            _ConnectionString = value
            Connect()

        End Set
    End Property

    Private _PeriodID As Integer
    <Browsable(True), DefaultValue(0), Description("If property is not 0 then only show providers who have approved funding in that year")> _
    Public Property zPeriodID() As Integer
        Get
            Return _PeriodID
        End Get
        Set(ByVal value As Integer)
            _PeriodID = value
            Connect()
        End Set
    End Property


    Private _ShowNonRelationships As Boolean
    <Browsable(True), DefaultValue(False), Description("Show providers that have no relationships")> _
    Public Property zShowNonRelationships() As Boolean
        Get
            Return _ShowNonRelationships
        End Get
        Set(ByVal value As Boolean)
            _ShowNonRelationships = value
        End Set
    End Property


    Private _LACodeFilter As String
    <Browsable(True), DefaultValue(""), Description("If property is not blank then filter providers by the LA Code")> _
    Public Property zLACodeFilter() As String
        Get
            Return _LACodeFilter
        End Get
        Set(ByVal value As String)
            _LACodeFilter = value
            Connect()

        End Set
    End Property

    Private _TerritoryCodeFilter As String
    <Browsable(True), DefaultValue(""), Description("If property is not blank then filter providers by the Territory Code")> _
    Public Property zTerritoryCodeFilter() As String
        Get
            Return _TerritoryCodeFilter
        End Get
        Set(ByVal value As String)
            _TerritoryCodeFilter = value
            Connect()

        End Set
    End Property


    Private _ProviderTypeCodeFilter As String
    <Browsable(True), DefaultValue(""), Description("If property is not blank then filter providers by the provider type code")> _
    Public Property zProviderTypeCodeFilter() As String
        Get
            Return _ProviderTypeCodeFilter
        End Get
        Set(ByVal value As String)
            _ProviderTypeCodeFilter = value
            Connect()

        End Set
    End Property


    Private _SelectedProvider As New SelectedProviderClass
    <Browsable(False), Description("The current selected provider")> _
    Public ReadOnly Property zSelectedProvider() As SelectedProviderClass
        Get
            Return _SelectedProvider
        End Get

    End Property


    Private _AllOptionAvailable As Boolean
    <Browsable(True), DefaultValue(False), Description("Territory Box <All> option available")> _
    Public Property zAllOptionAvailable() As Boolean
        Get
            Return _AllOptionAvailable
        End Get
        Set(ByVal value As Boolean)
            _AllOptionAvailable = value
        End Set
    End Property


    Private _Connected As Boolean
    <Browsable(False), DefaultValue(False), Description("Was the connection successfuly made")> _
    Public ReadOnly Property zConnected() As Boolean
        Get
            Return _Connected
        End Get

    End Property



    'ProviderSelected Event settings
    Class SelectedProviderClass
        Public RID As String
        Public UPIN As Integer
        Public ProviderName As String
        Public LAName As String
        Public TerritoryName As String
        Public LACode As String
        Public TerritoryCode As String
        Public UAI As String
    End Class

    <Browsable(True), Description("Event is raised when a provider has been selected.")> _
    Public Event ProviderSelected(ByVal e As SelectedProviderClass)

    <Browsable(True), Description("Event is raised when a provider has been deselected.")> _
    Public Event ProviderDeselected()


    Private Sub ShowPopupGrid()

        If _Connected = False Then Exit Sub

        If IsNothing(host) Then
            Exit Sub
        End If

        popup.Margin = Padding.Empty
        popup.Padding = Padding.Empty

        host.Margin = Padding.Empty
        host.Padding = Padding.Empty

        If popup.Items.Count <> 1 Then
            popup.Items.Add(host)
        End If

        popup.Show(TheTextBox, 0, TheTextBox.Height)
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        LoadData(Trim(TheTextBox.Text))
        ShowPopupGrid()
    End Sub

    Private Sub SetupPanel()

        If tp.Controls.Count = 0 Then
            tp.BorderStyle = Windows.Forms.BorderStyle.None

            RemoveHandler pg.CellMouseClick, AddressOf GridCellMouseClick
            RemoveHandler pg.KeyDown, AddressOf GridKeyDown

            AddHandler pg.CellMouseClick, AddressOf GridCellMouseClick
            AddHandler pg.KeyDown, AddressOf GridKeyDown

            tp.Controls.Add(pg)

            host = New ToolStripControlHost(tp)
        End If

    End Sub

    Private Sub GridCellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)
        If _Connected Then
            SelectMe(e.RowIndex)
        End If
    End Sub

    Private Sub GridKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If _Connected = False Then Exit Sub

        If e.KeyCode = Keys.Enter Then

            If pg.SelectedRows.Count = 0 Then Exit Sub
            SelectMe(pg.SelectedRows(0).Index)
            e.SuppressKeyPress = True

        End If
    End Sub

    Public Sub ClearSelected()

        Dim RunEvent As Boolean = False

        If _SelectedProvider.RID <> "" Then
            RunEvent = True
        End If

        _SelectedProvider.LACode = ""
        _SelectedProvider.LAName = ""
        _SelectedProvider.ProviderName = ""
        _SelectedProvider.RID = ""
        _SelectedProvider.TerritoryCode = ""
        _SelectedProvider.TerritoryName = ""
        _SelectedProvider.UPIN = -1
        _SelectedProvider.UAI = ""

        TheTextBox.BackColor = ColorTranslator.FromHtml("#FFE0C0")

        If RunEvent Then
            RaiseEvent ProviderDeselected()
        End If

    End Sub

    Public Sub SetProviderByRID(ByVal RID As String)

        dv.RowFilter = "RID = '" & RID & "'"

        If dv.Count = 0 Then
            dv.RowFilter = ""
            Exit Sub
        End If

        _SelectedProvider.LACode = dv(0)("LA_Code")
        _SelectedProvider.LAName = dv(0)("LA_Name")
        _SelectedProvider.ProviderName = dv(0)("Provider_Name")
        _SelectedProvider.RID = RID
        _SelectedProvider.TerritoryCode = dv(0)("Territory_Code")
        _SelectedProvider.TerritoryName = dv(0)("Territory_Name")
        _SelectedProvider.UPIN = dv(0)("UPIN")
        _SelectedProvider.UAI = IIf(IsDBNull(dv(0)("UAI")), "", dv(0)("UAI"))

        TheTextBox.Text = dv(0)("Provider_Name")
        TheTextBox.BackColor = ColorTranslator.FromHtml("#C0FFC0")

        dv.RowFilter = ""

        Dim esend As New SelectedProviderClass

        esend.RID = _SelectedProvider.RID
        esend.UPIN = _SelectedProvider.UPIN
        esend.ProviderName = _SelectedProvider.ProviderName
        esend.TerritoryName = _SelectedProvider.TerritoryName
        esend.LAName = _SelectedProvider.LAName
        esend.LACode = _SelectedProvider.LACode
        esend.TerritoryCode = _SelectedProvider.TerritoryCode
        esend.UAI = _SelectedProvider.UAI

        RaiseEvent ProviderSelected(esend)
    End Sub


    Private Sub SelectMe(ByVal CurrentRow As Integer)
        If _Connected = False Then Exit Sub

        If CurrentRow < 0 Then Exit Sub

        TheTextBox.Text = pg.Item("Provider_Name", CurrentRow).Value


        If pg.Item("UPIN", CurrentRow).Value = "<All>" Then
            _SelectedProvider.UPIN = 0
            _SelectedProvider.ProviderName = ""

        Else
            _SelectedProvider.UPIN = pg.Item("UPIN", CurrentRow).Value
            _SelectedProvider.ProviderName = pg.Item("Provider_Name", CurrentRow).Value
        End If

        _SelectedProvider.RID = pg.Item("RID", CurrentRow).Value
        _SelectedProvider.TerritoryName = pg.Item("Territory_Name", CurrentRow).Value
        _SelectedProvider.LAName = pg.Item("LA_Name", CurrentRow).Value
        _SelectedProvider.LACode = pg.Item("LA_Code", CurrentRow).Value
        _SelectedProvider.TerritoryCode = pg.Item("Territory_Code", CurrentRow).Value
        _SelectedProvider.UAI = pg.Item("UAI", CurrentRow).Value

        TheTextBox.BackColor = ColorTranslator.FromHtml("#C0FFC0")

        '   TheTextBox.Focus()
        popup.Hide()

        Dim esend As New SelectedProviderClass

        esend.RID = _SelectedProvider.RID
        esend.UPIN = _SelectedProvider.UPIN
        esend.ProviderName = _SelectedProvider.ProviderName
        esend.TerritoryName = _SelectedProvider.TerritoryName
        esend.LAName = _SelectedProvider.LAName
        esend.LACode = _SelectedProvider.LACode
        esend.TerritoryCode = _SelectedProvider.TerritoryCode
        esend.UAI = _SelectedProvider.UAI

        RaiseEvent ProviderSelected(esend)

    End Sub

    Private Sub LoadData(ByVal Filter As String)

        If _Connected = False Then Exit Sub

        pg.Rows.Clear()

        If IsNothing(dv) Then Exit Sub

        Dim filterstr As String = ""

        Filter = Filter.Replace("'", "''")

        If Filter <> "<All Providers>" Then
            filterstr = "UPIN like '%" & Filter & "%' OR Provider_Name like '%" & Filter & "%' OR LA_Name like '%" & Filter & "%' OR Territory_Name like '%" & Filter & "&'"
        End If

        dv.RowFilter = filterstr

        Dim i As Integer = 0
        Dim s As Integer = 0


        If _AllOptionAvailable Then

            pg.Rows.Add()
            pg.Item("RID", 0).Value = ""
            pg.Item("UPIN", 0).Value = "<All>"
            pg.Item("Provider_Name", 0).Value = "<All Providers>"
            pg.Item("LA_Name", 0).Value = ""
            pg.Item("Territory_Name", 0).Value = ""
            pg.Item("LA_Code", 0).Value = ""
            pg.Item("Territory_Code", 0).Value = ""
            pg.Item("UAI", 0).Value = ""

            s = 1
        Else
            s = 0
        End If

        For i = 0 To dv.Count - 1
            pg.Rows.Add()
            pg.Item("RID", i + s).Value = dv(i).Item("RID")
            pg.Item("UPIN", i + s).Value = dv(i).Item("UPIN")
            pg.Item("Provider_Name", i + s).Value = dv(i).Item("Provider_Name")
            pg.Item("LA_Name", i + s).Value = dv(i).Item("LA_Name")
            pg.Item("Territory_Name", i + s).Value = dv(i).Item("Territory_Name")
            pg.Item("LA_Code", i + s).Value = dv(i).Item("LA_Code")
            pg.Item("Territory_Code", i + s).Value = dv(i).Item("Territory_Code")
            pg.Item("UAI", i + s).Value = dv(i).Item("UAI").ToString

        Next


    End Sub

    Private Sub LoadTheView()

        If _ConnectionString = "" Then
            _Connected = False
            Exit Sub
        End If

        Dim NoRelSQL As String

        NoRelSQL = " UNION select 'NORID' as RID, cast(p.UPIN as nvarchar(10)) as UPIN, Provider_Name, 'No Local Authority' as LA_Name, " & _
                "'No Territory' as Territory_Name, 'NOLA' as LA_Code, 'NOTC' as Territory_Code, UAI from Providers p " & _
                "left outer join Relationships r " & _
                "on (p.UPIN = r.UPIN) " & _
                "where r.UPIN is null"

        Dim sql As String = "select RID, cast(UPIN as nvarchar(10)) as UPIN, Provider_Name, LA_Name, Territory_Name, LA_Code, Territory_Code, UAI from all_Provider_fields where lead = 1 "

        If _PeriodID <> 0 Then
            sql = sql & "and RID in (select distinct RID from Allocations where Period_ID = " & _PeriodID & " and Status = 'Approved') "
        End If

        If _TerritoryCodeFilter <> "" Then
            sql = sql & "and Territory_Code = '" & _TerritoryCodeFilter & "' "
        End If

        If _LACodeFilter <> "" Then
            sql = sql & "and LA_Code = '" & _LACodeFilter & "' "
        End If

        If _ProviderTypeCodeFilter <> "" Then
            sql = sql & "and Provider_Type_Code = '" & _ProviderTypeCodeFilter & "' "
        End If

        If _ShowNonRelationships = True Then
            sql = sql & NoRelSQL
        End If

        Dim success As Boolean = True

        Dim p As New List(Of Object)
        p.Clear()

        p.Add(sql)
        p.Add("Preparing the data, please wait...")

        DoSomeWork("LoadBusyDataView", p, False)

        dv = BusyButFine.ReturnedValues(0)

        ' dv = LoadDataViewCtrl(sql, _ConnectionString, success)

        If dv Is Nothing Then
            success = False
        Else
            success = True
        End If


        If success Then
            _Connected = True
        Else
            _Connected = False
        End If

    End Sub

    Private Function Connect() As Boolean

        If _ConnectionString = "" Then

            Return False
            Exit Function
        End If

        ClearSelected()
        TheTextBox.Text = ""
        SetupPanel()

        LoadTheView()

        If _Connected Then

            pg.Width = 600
            pg.Height = 300

            pg.MultiSelect = False

            pg.RowHeadersVisible = False
            pg.BackgroundColor = Color.White

            pg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.Fill
            pg.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
            pg.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing


            pg.AllowUserToResizeRows = False
            pg.AllowUserToDeleteRows = False

            pg.AllowUserToAddRows = False

            pg.AutoGenerateColumns = True

            pg.Columns.Clear()

            pg.Columns.Add("RID", "RID")
            pg.Columns.Add("UPIN", "UPIN")
            pg.Columns.Add("Provider_Name", "Provider Name")
            pg.Columns.Add("LA_Name", "Local Authority")
            pg.Columns.Add("Territory_Name", "Territory")
            pg.Columns.Add("LA_Code", "LA Code")
            pg.Columns.Add("Territory_Code", "Territory Code")
            pg.Columns.Add("UAI", "UAI")

            pg.Columns("RID").Visible = False
            pg.Columns("LA_Code").Visible = False
            pg.Columns("Territory_Code").Visible = False
            pg.Columns("UAI").Visible = False

            pg.Columns("UPIN").Width = 50
            pg.Columns("Provider_Name").Width = 300
            pg.Columns("Territory_Name").Width = 60

            pg.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single

            pg.MultiSelect = False
            pg.ReadOnly = True
            pg.SelectionMode = DataGridViewSelectionMode.FullRowSelect

            pg.ScrollBars = ScrollBars.Vertical

            Return True
        Else
            Return False
        End If

    End Function

    Private Sub TheTextBox_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TheTextBox.KeyPress
        If _Connected = False Then Exit Sub

        If e.KeyChar = Chr(13) Then
            LoadData(Trim(TheTextBox.Text))
            ShowPopupGrid()
            pg.Focus()
        Else

            ClearSelected()
        End If
    End Sub


End Class







